package com.mybatis.lo.handler;

import com.mybatis.lo.config.MappedStatement;
import com.mybatis.lo.utils.ReflectionUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 默认的结果解析器
 * @author zhangbh
 * 2023-06-20 08:49
 **/
public class DefaultResultSetHandler implements ResultSetHandler {

    private final MappedStatement mappedStatement;
    private final Class<?> resultType;

    public DefaultResultSetHandler(MappedStatement mappedStatement, Class<?> resultType) {
        this.mappedStatement = mappedStatement;
        this.resultType = resultType;
    }

    @Override
    public <T> List<T> handleResultSets(Statement ps) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        ResultSet rs = ps.getResultSet();
        if (resultType == null) {
            System.out.println("传入类型为空哦 resultType");
            return null;
        }
        List<T> result = new ArrayList<>();
        while (rs.next()) {
            T data = ReflectionUtils.newInstance(resultType);
            ResultSetMetaData metaData = rs.getMetaData();
            // 通过字段名+反射设置值
            int count = metaData.getColumnCount();
            for (int i = 0; i < count; i++) {
                String fieldName = metaData.getColumnName(i + 1);
                Object fieldValue = rs.getObject(fieldName);
                // todo 这边可以通过TypeHandler进行解析设置从 JDBC数据类型转换成java类型
                // Field field = ReflectionUtils.getField(data, fieldName);
                ReflectionUtils.setFieldValue(data, fieldName, fieldValue);
            }
            // 加入返回数据
            result.add(data);
        }
        return result;
    }
}
